package service

import (
	"encoding/xml"
	"engine/dto"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"lib/db"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

const receiverId = "ww57caa1e0577d37e9"
const encodingAeskey = "WagvmsXsPAaPTJUAM19ygQzsIYEwGvTDniOQuTGVpt4"

func getString(str, endstr string, start int, msg *string) int {
	end := strings.Index(str, endstr)
	*msg = str[start:end]
	return end + len(endstr)
}

func VerifyURL(w http.ResponseWriter, r *http.Request) {
	//httpstr := `&{GET /?msg_signature=825075c093249d5a60967fe4a613cae93146636b&timestamp=1597998748&nonce=1597483820&echostr=neLB8CftccHiz19tluVb%2BUBnUVMT3xpUMZU8qvDdD17eH8XfEsbPYC%2FkJyPsZOOc6GdsCeu8jSIa2noSJ%2Fez2w%3D%3D HTTP/1.1 1 1 map[Cache-Control:[no-cache] Accept:[*/*] Pragma:[no-cache] User-Agent:[Mozilla/4.0]] 0x86c180 0 [] false 100.108.211.112:8893 map[] map[] <nil> map[] 100.108.79.233:59663 /?msg_signature=825075c093249d5a60967fe4a613cae93146636b&timestamp=1597998748&nonce=1597483820&echostr=neLB8CftccHiz19tluVb%2BUBnUVMT3xpUMZU8qvDdD17eH8XfEsbPYC%2FkJyPsZOOc6GdsCeu8jSIa2noSJ%2Fez2w%3D%3D <nil>}`
	fmt.Println(r, r.Body)
	httpstr := r.URL.RawQuery
	start := strings.Index(httpstr, "msg_signature=")
	start += len("msg_signature=")

	var msg_signature string
	next := getString(httpstr, "&timestamp=", start, &msg_signature)

	var timestamp string
	next = getString(httpstr, "&nonce=", next, &timestamp)

	var nonce string
	next = getString(httpstr, "&echostr=", next, &nonce)

	echostr := httpstr[next:len(httpstr)]

	echostr, _ = url.QueryUnescape(echostr)
	fmt.Println(msg_signature, timestamp, nonce, echostr, next)

	wxcpt := NewWXBizMsgCrypt(token, encodingAeskey, receiverId, XmlType)
	echoStr, cryptErr := wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
	if nil != cryptErr {
		fmt.Println("verifyUrl fail", cryptErr)
	}
	fmt.Println("verifyUrl success echoStr", string(echoStr))
	fmt.Fprintf(w, string(echoStr))

}

type MsgContent struct {
	ToUsername   string `json:"ToUserName"`
	FromUsername string `json:"FromUserName"`
	CreateTime   uint32 `json:"CreateTime"`
	MsgType      string `json:"MsgType"`
	Content      string `json:"Content"`
	Msgid        uint64 `json:"MsgId"`
	Agentid      uint32 `json:"AgentId"`
}

func MsgHandler(w http.ResponseWriter, r *http.Request) []byte {
	httpstr := r.URL.RawQuery
	start := strings.Index(httpstr, "msg_signature=")
	start += len("msg_signature=")

	var msg_signature string
	next := getString(httpstr, "&timestamp=", start, &msg_signature)

	var timestamp string
	next = getString(httpstr, "&nonce=", next, &timestamp)

	nonce := httpstr[next:len(httpstr)]
	fmt.Println(msg_signature, timestamp, nonce)

	body, err := ioutil.ReadAll(r.Body)
	fmt.Println(string(body), err)
	wxcpt := NewWXBizMsgCrypt(token, encodingAeskey, receiverId, XmlType)

	msg, err_ := wxcpt.DecryptMsg(msg_signature, timestamp, nonce, body)
	fmt.Println(string(msg), err_)

	var msgContent MsgContent
	err = xml.Unmarshal(msg, &msgContent)
	if nil != err {
		fmt.Println("Unmarshal fail")
	} else {
		msgss := "未找到数据"
		if msgContent.MsgType != "text" {
			return nil
		}
		//20231898
		content := msgContent.Content
		fmt.Println(content, len(content))
		if len(content) == 14 {
			ss := "数据"
			fmt.Println(content[:5])
			if strings.Contains(ss, content[:5]) {
				//查询资产c
				cc := content[6:]
				num, err := strconv.Atoi(cc)
				if err != nil {
					fmt.Println("转换错误:", err)
					return nil
				}

				user, err := dto.GetSysUserDetailById(uint64(num))
				if err != nil {
					fmt.Println(err)
					msgss = "未找到用户"
				} else {
					var count int64
					db.GetDb().Table("my_user").Where("pid = ?", user.Id).Count(&count)

					pmobile := ""
					if user.Pid > 0 {
						puser, err := dto.GetSysUserDetailById(uint64(user.Pid))
						if err == nil && puser.Id > 0 {
							pmobile = puser.Mobile
						}
					}
					f := "未封禁"
					if user.F == 1 {
						f = "已封禁"
					}
					isTask := "否"
					if user.IsTask == 1 {
						isTask = "有效用户"
					}
					msgss = fmt.Sprintf("手机号：%s\n上级ID：%v\n上级手机号：%v\n通用积分：%v\n贡献积分：%v\n直推人数：%v\n是否认证：%v\n是否封禁：%v\n昨天等级：%v\n当前等级：%v\n加入时间：%s",
						user.Mobile,
						user.Pid,
						pmobile,
						user.Money,
						user.Point,
						count,
						isTask,
						f,
						user.OldLevel,
						user.Level,
						user.CreateTime[:16],
					)

				}
			}
		}
		respData1 := "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msgss + "]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>"
		encryptMsg, cryptErr := wxcpt.EncryptMsg(respData1, timestamp, nonce)
		if nil != cryptErr {
			fmt.Println("DecryptMsg fail", cryptErr)
		}
		return encryptMsg

	}
	return nil
}

func CallbackHandler(c *gin.Context) {

	r := c.Request
	w := c.Writer

	httpstr := r.URL.RawQuery
	echo := strings.Index(httpstr, "echostr")
	if echo != -1 {
		VerifyURL(w, r)
	} else {
		ss := MsgHandler(w, r)
		c.Data(200, "application/xml", ss)
	}

	fmt.Println("finished CallbackHandler", httpstr)
}
